package com.kilomob.grady.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kilomob.grady.rpc.Invoker;
import com.kilomob.grady.rpc.RpcInvocation;

public class InvokerInvocationHandler implements InvocationHandler {
    private static Logger LOGGER = LoggerFactory.getLogger(InvokerInvocationHandler.class);

    private final Invoker<?> invoker;
    
    private String interfaceName;
    
    public InvokerInvocationHandler(Invoker<?> handler){
        this.invoker = handler;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(invoker, args);
        }
        if ("toString".equals(methodName) && parameterTypes.length == 0) {
            return invoker.toString();
        }
        if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
            return invoker.hashCode();
        }
        if ("equals".equals(methodName) && parameterTypes.length == 1) {
            return invoker.equals(args[0]);
        }
        try{
            
            return invoker.invoke(new RpcInvocation(this.invoker.getClass().getName(),method, args));
        }catch(Exception e){
            LOGGER.error("invoke error:",e);
        }
        return null;
    }

    public String getInterfaceName() {
        return interfaceName;
    }

    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
    }
    
    

}